package com.liu.netty.demo;

import com.liu.netty.demo.client.DemoServer;
import com.liu.netty.demo.client.EchoByteArrayChannelHandler;
import com.liu.netty.demo.client.EchoChannelHandler;
import com.liu.netty.demo.client.HeartBeatServerHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.bytes.ByteArrayDecoder;
import io.netty.handler.codec.bytes.ByteArrayEncoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.nio.ByteOrder;
import java.util.concurrent.TimeUnit;

/**
 * @program: https://www.joinsunsoft.com
 * @description:
 * @author: LiuYong
 * @email: david.liu@ginghan.com
 * @create: 2022/3/22 21:02
 */

@Component
@Slf4j
public class DemoServerStarter {

    @Value("${netty.port}")
    private Integer port;

    @Value("${netty.name}")
    private String name;

    private DemoServer demoServer;

    @PostConstruct
    public void start(){
//        demoServer = new DemoServer() {
//            @Override
//            protected ChannelHandler[] initHandler() {
//                return new ChannelHandler[]{
//                        new StringDecoder(),
//                        new StringEncoder(),
//                        new EchoChannelHandler()
//                };
//            }
//        };

        demoServer = new DemoServer() {
            @Override
            protected ChannelHandler[] initHandler() {
                return new ChannelHandler[]{
                        new LengthFieldBasedFrameDecoder(ByteOrder.BIG_ENDIAN,
                            655360,0,
                                2,0,0,true),
                        new ByteArrayEncoder(),
                        new ByteArrayDecoder(),
                        new EchoByteArrayChannelHandler()
                };
            }
        };

        demoServer.setName(name);
        demoServer.setPort(port);

        demoServer.start();
    }

    @PreDestroy
    public void destory(){
        if(demoServer!=null)
            demoServer.destory();
    }

//    /**
//     * boss 线程组用于处理连接工作
//     */
//    private EventLoopGroup boss = new NioEventLoopGroup();
//    /**
//     * work 线程组用于数据处理
//     */
//    private EventLoopGroup work = new NioEventLoopGroup();
//
//
//    @PostConstruct
//    public void start(){
//
//        ServerBootstrap bootstrap = new ServerBootstrap();
//
//        ChannelFuture future = null;
//
//        bootstrap.group(boss,work);
//
//
//        try{
//
//            bootstrap.channel(NioServerSocketChannel.class);
//
//            bootstrap.childHandler(new ChannelInitializer<Channel>() {
//                @Override
//                protected void initChannel(Channel channel) throws Exception {
//                    channel.pipeline().addLast(new IdleStateHandler(300,300,600, TimeUnit.SECONDS));
////                    channel.pipeline().addLast(new LengthFieldBasedFrameDecoder(ByteOrder.BIG_ENDIAN,
////                            655360,0,2,0,2,true));
//                    channel.pipeline().addLast(new HeartBeatServerHandler());
//                    channel.pipeline().addLast(new StringDecoder());
//                    channel.pipeline().addLast(new StringEncoder());
//                    channel.pipeline().addLast(new EchoChannelHandler());
//                }
//            });
//
//            bootstrap.option(ChannelOption.SO_BACKLOG, 2048);//serverSocketchannel的设置，链接缓冲池的大小
//            bootstrap.childOption(ChannelOption.SO_KEEPALIVE, true);//socketchannel的设置,维持链接的活跃，清除死链接
//            bootstrap.childOption(ChannelOption.TCP_NODELAY, true);//socketchannel的设置,关闭延迟发送
//
//            future = bootstrap.bind(port).sync();
//
//            if(future.isSuccess()){
//                log.info("Server {}[:{}] is  started !!!", name, port);
//            }
//            else{
//                log.info("Server {}[:{}] is  started fail!!!", name, port);
//            }
//
//            //future.channel().closeFuture().sync();
//
//        }catch (Throwable t)
//        {
//            log.error("{}[:{}] error", name, port);
//            log.error("error:", t);
//        }
//    }
//
//
//    @PreDestroy
//    public void destory() throws InterruptedException {
//        if(boss!=null)
//            boss.shutdownGracefully().sync();
//        if(work!=null)
//            work.shutdownGracefully().sync();
//
//        log.info("关闭{}[:{}]", name, port);
//    }

}
